package com.apksources.torch;

import com.bwf.example.light.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;

public class MainActivity extends Activity {
	public static MainActivity mInstance;
	private LinearLayout mSurfaceViewWrap;
	private ImageButton mStateOnBtn;
	private ImageButton mStateOffBtn;
	private boolean mIsTurnedOn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		MainActivity.mInstance = this;
	}

	@Override
	protected void onResume() {
		this.mIsTurnedOn = TorchService.isTorchTurnedOn();
		this.updateView();
		super.onResume();
	}

	/**
	 * 初始化界面，设置图片按钮点击响应时间
	 */
	private void initView() {

		this.mSurfaceViewWrap = (LinearLayout) findViewById(R.id.surface_view_wrap);

		/* 打开手电筒状态的图片按钮，点击设置手电筒关闭 */
		this.mStateOnBtn = (ImageButton) findViewById(R.id.state_on);
		this.mStateOnBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (mIsTurnedOn) {
					turnOffLight();
				}
			}
		});
		/* 关闭手电筒状态的图片按钮，点击设置手电筒打开 */
		this.mStateOffBtn = (ImageButton) findViewById(R.id.state_off);
		this.mStateOffBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (!mIsTurnedOn) {
					turnOnLight();
				}
			}
		});
	}

	/**
	 * 根据手电筒的状态更新界面
	 */
	private void updateView() {
		if (mIsTurnedOn) {
			this.mStateOffBtn.setVisibility(View.GONE);
		} else {
			this.mStateOffBtn.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 打开手电筒
	 */
	private void turnOnLight() {
		mIsTurnedOn = true;
		// 更新界面
		updateView();
		Intent service = new Intent(MainActivity.this, TorchService.class);
		service.putExtra(TorchService.SWITCH, TorchService.SWITCH_ON);
		startService(service);

	}

	/**
	 * 关闭手电筒
	 */
	private void turnOffLight() {
		mIsTurnedOn = false;
		// 更新界面
		updateView();
		Intent service = new Intent(MainActivity.this, TorchService.class);
		service.putExtra(TorchService.SWITCH, TorchService.SWITCH_OFF);
		startService(service);

	}

	/**
	 * 增加mSurfaceView到LinearLayout中
	 */
	public void addSurfaceView(MySurfaceView mySurfaceView) {
		this.mSurfaceViewWrap.removeAllViews();
		this.mSurfaceViewWrap.addView(mySurfaceView);
	}
}
